#include <iostream>
#include <unistd.h>
#include <fstream>
#include <string>
#include "../logs/log.h"
#include <mysql/mysql.h>
#include <cstring>
#include <errno.h>

using namespace define_log;

int main()
{
    std::string methon = getenv("METHOD");
    std::string paramenter; //CGI 获取目标文章的主键，这里就只有目标文章的主键

    int post_length = 0;
    if (methon == "GET")
    {
        paramenter = getenv("PARAMENTER");
    }else if (methon == "POST")
    {
        //1.获取先出发来CGI的参数信息
        post_length = atoi(getenv("CONTENT-LENHTH"));
        while (post_length > 0)
        {
            char x = 'g';
            int bx =  read(0, &x, 1);
            if (bx == -1)
                std::cerr << strerror(errno) << std::endl;

            paramenter.push_back(x);
            post_length--;
        }
    }
 
    //2.解析正文，并给予运算。这里只用输出一个数来表示CGI结果
    std::string it = "\r\n\r\n";
    std::string title, content;
    int cur = 0;
    for (int i = 1; i <= 2; i++)
    {
        cur = paramenter.find("\r\n\r\n", cur) + it.size(); 
        char ch = 'g';
        while (ch != '\r')
        {
            ch = paramenter[cur++];
            i == 1 ? title += ch : content += ch;
        }
        cur += it.size();
    }
    // std::cerr<< "title:" << title << std::endl;
    // std::cerr << "content:" << content << std::endl;

    //登录连接数据库
    MYSQL *conn;
    const char *server = "xxxxx";
    const char *user = "afeng";
    const char *password = "xxxx";
    const char *database = "blog_system";
    conn = mysql_init(NULL);

    if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) {
        std::cerr << mysql_error(conn) << std::endl;
        mysql_close(conn);
        return 1;
    }
    mysql_set_character_set(conn, "utf8");
    // 指令
    std::string str = "insert blog(title, content) values(\'";
    str += title;
    str += "\', \'";
    str += content;
    str += "\')";
    if (mysql_query(conn, str.c_str())) {
        std::cerr << mysql_error(conn) << std::endl;
        mysql_close(conn);
        return 1;
    }
    std::cout << "Content-Type: application/json; charset=utf-8\r\r"; 
    std::cout << "{\"status\":\"success\",\"message\":\"文章已成功发布！\"}" << std::endl;

    mysql_close(conn);

    //马上退出，有没有都差不多
    if (methon == "POST")
    {
        close(1);
        close(0);
    }
    return 0;
}